package write;

import java.io.*;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class OutputXMLString {
    private static String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
                                 + "<catalog>"
                                 + "<book id=\"1\">"
                                 + "<author>Charles Dickens</author>"
                                 + "<title>Oliver Twist</title>"
                                 + "</book>"
                                 + "</catalog>";

    public static void main(String[] args) throws Exception {
    DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
    DocumentBuilder b = f.newDocumentBuilder();
    Document doc = b.parse(new ByteArrayInputStream(xmlStr.getBytes("UTF-8")));

    Element catalog = (Element) doc.getElementsByTagName("catalog").item(0);

    // add Mark Twain book
    Element tom = doc.createElement("book");
    catalog.appendChild(tom);

    Attr attr = doc.createAttribute("id");
    attr.setValue("2");
    tom.setAttributeNode(attr);

    // author
    Element author = doc.createElement("author");
    author.appendChild(doc.createTextNode("Mark Twain"));
    tom.appendChild(author);

    // title
    Element title = doc.createElement("title");
    title.appendChild(doc.createTextNode("The Adventures of Tom Sawyer"));
    tom.appendChild(title);
   
    // output XML with transformer
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t = tf.newTransformer();
    DOMSource src = new DOMSource(doc);
    StreamResult res = new StreamResult(System.out);
    t.transform(src, res);
    }
}